package com.appkubes.mall.restful.application.user.account.account.service.impl;

import com.appkubes.common.exception.BusinessException;
import com.appkubes.common.utils.data.date.DateUtils;
import com.appkubes.mall.core.common.constants.MallUserAccountHistoryConstants;
import com.appkubes.mall.core.entity.MallUserAccount;
import com.appkubes.mall.core.entity.MallUserAccountHistory;
import com.appkubes.mall.core.service.impl.BaseMallUserAccountServiceImpl;
import com.appkubes.mall.restful.application.user.account.account.entity.dto.OrderPayUserAccountDTO;
import com.appkubes.mall.restful.application.user.account.account.service.UserAccountService;
import com.appkubes.mall.restful.application.user.account.history.service.UserAccountHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @Author: Rongjie
 * @Date: 2020/1/13 21:32
 * @Description:
 */
@Service
@Slf4j
public class UserAccountServiceImpl extends BaseMallUserAccountServiceImpl implements UserAccountService {

    @Resource
    UserAccountHistoryService accountHistoryService;

    @Resource
    UserAccountHistoryService userAccountHistoryService;

    @Override
    public Boolean onOrderPay(OrderPayUserAccountDTO orderPayUserAccountDTO) {
        Boolean flag = this.addBrokerage(orderPayUserAccountDTO.getUserKey(), orderPayUserAccountDTO.getBrokerage());
        //增加佣金后，记录账户历史(但不进账)
        accountHistoryService.onOrderPay(orderPayUserAccountDTO);
        log.info("userKey:" + orderPayUserAccountDTO.getUserKey() + ", money:" + orderPayUserAccountDTO.getBrokerage());
        return true;
    }


    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public Boolean addBrokerage(String userKey, BigDecimal brokerage) {
        //添加佣金
        MallUserAccount userAccount = getUserAccount(userKey);
        userAccount.setTotalBrokerage(userAccount.getTotalBrokerage().add(brokerage));
        userAccount.setUpdateTime(DateUtils.getCurrentTimestamp());
        //增加历史记录
        return this.updateById(userAccount);
    }

    MallUserAccount getUserAccount(String userKey) {
        MallUserAccount userAccount = this.getById(userKey);
        if (userAccount == null) {
            userAccount = new MallUserAccount();
            userAccount.setUserKey(userKey);
            userAccount.setTotalBrokerage(BigDecimal.valueOf(0));
            userAccount.setCreateTime(DateUtils.DateToTimestamp(new Date()));
            userAccount.setUpdateTime(DateUtils.DateToTimestamp(new Date()));
            userAccount.setAppKey(null);
            this.saveOrUpdate(userAccount);
        }

        return userAccount;
    }

    /**
     * 确认订单
     *
     * @param userKey
     * @param orderKey
     * @return
     * @throws BusinessException
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean orderConfirm(String userKey, String orderKey) throws RuntimeException {
        MallUserAccountHistory accountHistory = userAccountHistoryService.getAccountOrderHistory(orderKey);
        log.info("orderConfirm accountHistory: {}", accountHistory);
        if (accountHistory != null && MallUserAccountHistoryConstants.State.PENDING.name().equalsIgnoreCase(accountHistory.getState())) {
            log.info("未发放，则进行发放操作:{}", accountHistory.getAccountSourceKey());
            //未发放，则进行发放操作
            //添加佣金
            MallUserAccount userAccount = getUserAccount(accountHistory.getUserKey()); //给用户确认佣金
            userAccount.setTotalBrokerage(userAccount.getTotalBrokerage().add(accountHistory.getBrokerage()));
            userAccount.setUpdateTime(DateUtils.getCurrentTimestamp());
            Boolean success = this.updateById(userAccount);
            if (!success) {
                throw new RuntimeException("发放佣金错误");
            }
            accountHistory.setState(MallUserAccountHistoryConstants.State.CONFIRM.name());
            success = userAccountHistoryService.updateById(accountHistory);
            if (!success) {
                throw new RuntimeException("更新账户状态错误");
            }
        }
        log.info("orderConfirm: userKey:{}, orderKey:{}", userKey, orderKey);
        return true;
    }


}
